package com.acdc.mqtt.service.impl;

import com.acdc.mqtt.service.MessageHandler;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
import com.acdc.mqtt.entity.MqttMsg;
import com.acdc.mqtt.entity.OtaReq;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.acdc.service.IIotModuleService;
import com.acdc.service.IIotModuleLogService;
import com.acdc.domain.IotModule;
import com.acdc.domain.IotModuleLog;
import com.acdc.domain.OtaVersionFile;
import com.acdc.service.IOtaVersionFileService;
import java.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import com.acdc.mqtt.service.IotModuleSender;
import com.acdc.domain.OtaSplit;
import java.util.List;

@Slf4j
@Component
public class OtaReqHandler implements MessageHandler {

    @Autowired
    private IIotModuleService iotModuleService;

    @Autowired
    private IIotModuleLogService iotModuleLogService;

    @Autowired
    private IotModuleSender iotModuleSender;

    @Autowired
    private IOtaVersionFileService otaVersionFileService;

    @Override
    public void handleMessage(String topic, String message) {
        String imei = topic.split("\\/")[2];
        log.info("IMIEI: {}, OtaReqHandler: {}", imei, message);

        try {
            MqttMsg<OtaReq> mqttMsg = new ObjectMapper().readValue(message, new TypeReference<MqttMsg<OtaReq>>() {});
            OtaReq otaReq = mqttMsg.getData();
            log.info("OtaReq: {}", otaReq);
            int sta = otaReq.getSta();         
            switch (sta) {
                case 0:
                    // 不能进入OTA
                    saveIotModuleLog(imei, "ota_mode_err", mqttMsg);
                    break;
                case 1:
                    // 正在请求OTA升级包
                    saveIotModuleLog(imei, "ota_updating", mqttMsg);
                    int req = otaReq.getReq();
                    sendOtaVersionFile(imei, req);
                    break;                    
                case 2:
                    // OTA异常终止
                    saveIotModuleLog(imei, "ota_failed", mqttMsg);
                    break;
                case 3:
                    // 请求OTA升级完成
                    saveIotModuleLog(imei, "ota_success", mqttMsg);
                    break;
                default:
            }
        } catch (JsonProcessingException e) {
            log.error("OtaReqHandler: {}", e.getMessage());
        }
    }

    private void saveIotModuleLog(String imei, String opType, MqttMsg<?> mqttMsg) {
        try {
            IotModule iotModule = iotModuleService.selectIotModuleByImei(imei);
            IotModuleLog iotModuleLog = new IotModuleLog();
            iotModuleLog.setIotModuleId(iotModule.getId());
            iotModuleLog.setOpType(opType);
            iotModuleLog.setOpData(mqttMsg.toString());
            iotModuleLog.setOpTime(LocalDateTime.now());
            iotModuleLogService.insertIotModuleLog(iotModuleLog);
        } catch (Exception e) {
            log.error("保存IoT模块日志失败: {}", e.getMessage());
        }
    }

    private void sendOtaVersionFile(String imei, int req) {
        OtaVersionFile otaVersionFile = otaVersionFileService.selectLatestOtaVersionFile();
        if (otaVersionFile == null) {
            log.error("OTA升级包不存在");
            return;
        }
        // List<OtaSplit> otaSplits = otaVersionFile.getOtaSplitList();
        // for (OtaSplit otaSplit : otaSplits) {
        //     iotModuleSender.sentOTA(imei, otaSplit.getSeqNum(), otaSplit.getLength(), otaSplit.getData(), otaSplit.getChecksum());
        // }
        OtaSplit otaSplitQuery = new OtaSplit();
        otaSplitQuery.setOtaVersionId(otaVersionFile.getId());
        otaSplitQuery.setSeqNum(req);
        OtaSplit otaSplit = otaVersionFileService.selectOtaSplitByOtaVersionIdAndSeqNum(otaSplitQuery);
        if (otaSplit == null) {
            log.error("OTA分割不存在");
            return;
        }
        String flag = "1";
        if (otaSplit.getSeqNum() == 1) {
            flag = "0";
        } 
        otaSplitQuery = new OtaSplit();
        otaSplitQuery.setOtaVersionId(otaVersionFile.getId());
        otaSplitQuery.setSeqNum(req + 1);
        OtaSplit nextOtaSplit = otaVersionFileService.selectOtaSplitByOtaVersionIdAndSeqNum(otaSplitQuery);
        if (nextOtaSplit == null) {
            flag = "2";
        }
        iotModuleSender.sentOTA(imei, otaSplit.getSeqNum(), otaSplit.getLength(), otaSplit.getData(), otaSplit.getChecksum(), flag);
    }
}
